<?php

use Illuminate\Database\Seeder;
use Yangyifan\Library\UtilityLibrary;

class NodesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        echo "Start: " . __CLASS__ . " \r\n";

        $children = [
            ['name' => '首页', 'method_name' => 'index'],
            ['name' => '搜索', 'method_name' => 'search'],
            ['name' => '获取单个数据', 'method_name' => 'show'],
            ['name' => '创建', 'method_name' => 'store'],
            ['name' => '更新', 'method_name' => 'update'],
            ['name' => '删除', 'method_name' => 'destroy'],
        ];

        $nodes = [
            ['name' => '配置', 'controller_name' => 'ConfigController', 'children' => []],
            ['name' => '管理员', 'controller_name' => 'Admin\\AdminController', 'children' => array_merge($children, [
                ['name' => '上传', 'method_name' => 'upload'],
            ])],
            ['name' => '菜单', 'controller_name' => 'Menus\\MenusController', 'children' => $children],
            ['name' => '节点', 'controller_name' => 'Nodes\\NodesController', 'children' => $children],
            ['name' => '角色', 'controller_name' => 'Roles\\RolesController', 'children' => array_merge($children, [
                ['name' => '获得菜单', 'method_name' => 'getMenus'],
                ['name' => '设置菜单', 'method_name' => 'setMenus'],
                ['name' => '获得节点', 'method_name' => 'getNodes'],
                ['name' => '设置节点', 'method_name' => 'setNodes'],
            ])],
        ];

        // 循环的去遍历添加
        foreach ($nodes as $node) {
            // 创建一个账户
            $parentId = $this->add($node);

            // 如果有子级，则继续新增子级
            if (UtilityLibrary::isArray($node['children'])) {
                foreach ($node['children'] as $childrenNode) {
                    $this->add(array_merge($childrenNode, ['parent_id' => $parentId, 'controller_name' => $node['controller_name']]));
                }
            }
        }

        echo "Finished: " . __CLASS__ . " \r\n";
    }

    /**
     * 添加数据
     *
     * @param $node
     *
     * @return int
     */
    protected function add($node)
    {
        $model = \Yangyifan\Administrator\Access\Model\Nodes\Nodes::create([
            'name'            => $node['name'],
            'controller_name' => isset($node['controller_name']) ? $node['controller_name'] : '',
            'method_name'     => isset($node['method_name']) ? $node['method_name'] : '',
            'parent_id'       => $node['parent_id'] ?? 0,
        ]);

        return $model->id;
    }
}
